package juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class TestABCAlternate {
    public static void main(String[] args) {
        AlternateDemo ad = new AlternateDemo();
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                ad.LoopA(i);
            }
        }, "A").start();
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                ad.LoopB(i);
            }
        }, "B").start();
        new Thread(()->{
            for (int i = 0; i < 5; i++) {
                ad.LoopC(i);
                System.out.println("----------");
            }
        }, "C").start();
    }
}


class AlternateDemo{
    private int number = 1;

    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();

    public void LoopA(int totalLoop){
        lock.lock();
        try{
            if(number != 1){
                condition1.await();
            }
            for (int i = 0; i < 1; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i + "\t" + totalLoop);
            }
            number = 2;
            condition2.signal();
        }catch(Exception e){

        }finally {
            lock.unlock();
        }
    }

    public void LoopB(int totalLoop){
        lock.lock();
        try{
            if(number != 2){
                condition2.await();
            }
            for (int i = 0; i < 1; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i + "\t" + totalLoop);
            }
            number = 3;
            condition3.signal();
        }catch(Exception e){

        }finally {
            lock.unlock();
        }
    }

    public void LoopC(int totalLoop){
        lock.lock();
        try{
            if(number != 3){
                condition3.await();
            }
            for (int i = 0; i < 1; i++) {
                System.out.println(Thread.currentThread().getName() + "\t" + i + "\t" + totalLoop);
            }
            number = 1;
            condition1.signal();
        }catch(Exception e){

        }finally {
            lock.unlock();
        }
    }
}